<template>
  <div class="search statusBar">
    <van-search v-model="value" placeholder="请输入搜索关键词" show-action shape="round" ref="search" @input="getSearchData" @search="goToSearchList(value)">
      <template #action>
        <div @click="returnBookcity">取消</div>
      </template>
    </van-search>
    <div class="box" v-if="isReady">
      <div v-if="searchStatus === 1">
        <dl class="recommend-box">
          <dt>搜索发现</dt>
            <dd class="search-find" v-for="(item, index) in recommendData[0]" :key="index" @click="goToSearchList(item.word)">{{item.word}}</dd>
          <dt>热搜书籍</dt>
            <dd>
              <ul>
                <li class="hot-book" v-for="(item, index) in recommendData[1]" :key="index" @click="goToSearchList(item.title)">
                  <div>
                    <i>{{index+1}}</i>
                    <img :src="item.cover" alt="">
                    <div>
                      <div class="title">{{item.title}}</div>
                      <div class="short-intro one-text">{{item.shortIntro}}</div>
                    </div>
                  </div>
                </li>
              </ul>
            </dd>
        </dl>
      </div>
      <div v-if="searchStatus === 2">
        <div class="search-box">
          <ul v-for="(item, index) in searchData" :key="index">
            <li v-for="(item2, index2) in item.data" :key="index2" @click="goToSearchList(item2)"><div class="search-key">{{item2}}</div><span v-if="item.isAuthor">/作者</span></li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  export default {
    name: 'Search',

    data() {
      return {
        // 推荐数据
        recommendData: [],
        // 搜索框
        value: '',
        // 防抖
        timer: null,
        time: 500,
        // 搜索数据
        searchData: [],
        // 加载完成
        isReady: false
      }
    },

    created() {
      // 获取焦点
      this.focus();

      // 获取推荐数据
      this.getRecommendData();

      if(this.searchKey) {
        this.value = this.searchKey;
        this.time = 0;
        this.getSearchData();
      }
    },

    computed: {
      // 搜索状态
      searchStatus() {
        return this.$store.state.sStatus;
      },

      // 搜索关键字
      searchKey() {
        return this.$store.state.sKey;
      }
    },

    methods: {
      // 获取焦点
      focus() {
        this.$nextTick(() => {
          this.$refs.search.querySelectorAll("input")[0].focus();
        });
      },

      // 获取推荐数据
      getRecommendData() {
        // 发现
        this.find();
      },

      // 发现
      find() {
        this.axios.get('search-hotwords')
        .then(res => {
          // console.log('find res', res);
          if(res.status == 200) {
            this.recommendData.push(res.data.searchHotWords.slice(0, 5));
            // 热门
            this.hot();
          }
        }).catch(err => {
          console.log('err', err);
        })
      },

      // 热门
      hot() {
        this.axios.get('hot-books')
        .then(res => {
          // console.log('hot res', res);
          let hot = [];
          if(res.status == 200) {
            res.data.hotWords.forEach(key => {
              this.axios.get('search', {
                params: {
                  keyword: key
                }
              }).then(res => {
                // console.log('res', res);
                if(res.status == 200) {
                    // 对图片url解码
                    res.data.books[0].cover = decodeURIComponent(res.data.books[0].cover.split('/')[2]);
                    hot.push(res.data.books[0]);
                }
              }).catch(err => {
                console.log('err', err);
              })
            })
          }
          this.recommendData.push(hot);
          this.isReady = true;
        }).catch(err => {
          console.log('err', err);
        })
      },

      // 修改搜索状态
      changeSearchStatus(status) {
        this.$store.commit('changeSearchStatus', status);
      },

      // 修改搜索值
      changeSearchKey(key) {
        this.$store.commit('changeSearchKey', key);
      },

      // 搜索数据
      getSearchData() {
        // 如果输入框为空
        if(!this.value) {
          this.changeSearchStatus(1);
          this.changeSearchKey(this.value);
          // 防抖
          if(this.timer) clearTimeout(this.timer);
          return;
        }
        // 防抖
        if(this.timer) clearTimeout(this.timer);
        this.timer = setTimeout(() => {
          this.axios.get('search', {
            params: {
              keyword: this.value
            }
          }).then(res => {
            // console.log('res', res);
            if(res.data.ok) {
              this.time = 500;
              // 修改搜索状态
              this.changeSearchStatus(2);
              // 处理后的数据
              let handleData = [];
              // 作者数组
              let authors = [];
              // 书籍数组
              let books = [];
              // 最多展示多少个作者
              let authorNumber = 3;
              // 记录已经存在的作者名和书名
              let markAuthor = '';
              let markBook = '';
              // 遍历请求的数据
              res.data.books.forEach(v => {
                  // 判断作者的数量是否超过最大限制
                  if(authorNumber > 0) {
                    // 判断作者名是否包含搜索的字符
                    if(v.author.indexOf(this.value) > -1) {
                      // 判断作者名是否已经存在
                      if(markAuthor.indexOf(v.author) == -1) {
                        authors.push(v.author);
                        markAuthor += v.author;
                        authorNumber--;
                      }
                    }
                  }
              })
              handleData.push({
                isAuthor: true,
                data: authors
              })
              // 最多展示多少条数据
              let dataNumber = 10 - authorNumber;
              res.data.books.forEach(v => {
                // 判断展示的数据是否超过最大限制
                if(dataNumber > 0) {
                  // 判断标题是否包含搜索的字符
                  if(v.title.indexOf(this.value) > -1) {
                    // 判断书名是否已经存在
                    if(markBook.indexOf(v.title) == -1) {
                      books.push(v.title);
                      markBook += v.title;
                      dataNumber--;
                    }
                  }
                }
              })
              handleData.push({
                isAuthor: false,
                data: books
              })
              this.searchData = handleData;
            }
          }).catch(err => {
            console.log('err', err);
          })
        }, this.time)
      },

      // 返回书城页
      returnBookcity() {
        this.changeSearchStatus(1);
        this.changeSearchKey('');
        this.$router.replace({name: 'BookCity'});
      },

      // 转到搜索列表页
      goToSearchList(key) {
        this.changeSearchKey(key);
        this.$router.push({name: 'SearchList', query: {isSearch: true}});
      },
    },
  }
</script>

<style lang="less" scoped>
::v-deep .van-search {
  position: sticky;
  top: 0;
  z-index: 999999;
}

.box {
  position: fixed;
  top: 54px + 28px;
  bottom: 0;
  left: 0;
  right: 0;
  overflow-y: auto;
}
.recommend-box {
  padding: 12px;
}
.recommend-box dt {
  margin: 10px 0;
  color: #999;
}
.recommend-box dd {
  color: #333;
}
.search-find {
  position: relative;
  display: inline-block;
  margin: 6px;
  padding: 6px 12px;
  background-color: #f7f8fa;
  border-radius: 26px;
}
.search-find:nth-of-type(1),
.search-find:nth-of-type(2) {
  padding-left: 30px;
  &::after {
    content: '';
    position: absolute;
    top: 50%;
    left: 8px;
    display: block;
    width: 15px;
    height: 15px;
    background: url(../assets/images/hot.png) center;
    background-color: #fff;
    transform: translateY(-50%);
    border-radius: 100%;
  }
}
.hot-book {
  position: relative;
}
.hot-book>div {
  display: flex;
  align-items: center;
  padding: 6px;
  color: #333;
}
.hot-book>div i {
  margin-right: 20px;
  color: #999;
  font-size: 16px;
  font-weight: bold;
}
.hot-book:nth-of-type(1)>div i,
.hot-book:nth-of-type(2)>div i,
.hot-book:nth-of-type(3)>div i {
  color: red;
}
.hot-book img {
  margin-right: 15px;
  width: 45px;
  border-radius: 1px;
  box-shadow: 1px 1px 2px #aaa;
}
.hot-book .title {
  color: #000;
  font-size: 14px;
}
.hot-book .short-intro {
  color: #999;
  font-size: 12px;
}
.hot-book .title,
.hot-book .short-intro {
  padding: 3px 0;
  max-width: 250px;
}
.hot-book {
  color: #999;
}
.hot-book:nth-of-type(1) .title,
.hot-book:nth-of-type(2) .title,
.hot-book:nth-of-type(3) .title {
  position: relative;
  display: inline-block;
  &::after {
    content: '热门';
    position: absolute;
    top: 50%;
    right: 0;
    padding: 0 3px;
    background-color: #ffe9ee;
    color: #ee0a24;
    font-size: 10px !important;
    font-weight: normal;
    transform: translateX(140%) translateY(-50%);
    border-radius: 3px;
  }
}
.search-box {
  padding: 12px;
}
.search-box li {
  padding: 12px;
  color: #333;
  font-size: 14px;
  border-bottom: 1px solid #f7f8fa;
}
.search-box li span {
  margin-left: 5px;
  color: #999;
  font-size: 12px;
}
.search-key {
  display: inline-block;
}


</style>